/*
 * @Author: YNT 2501512800@qq.com
 * @Date: 2022-08-06 23:09:23
 * @LastEditors: YNT 2501512800@qq.com
 * @LastEditTime: 2022-08-20 12:13:26
 * @FilePath: \20220806后台\src\router\index.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import Vue from "vue";
import Router from "vue-router";
import {getStorage} from "@/utils/service/auth";

Vue.use(Router);

/* Layout */
import Layout from "@/layout";


//#region 路由模块化
// const modulesFiles = require.context("./modules", true, /\.js$/);

const modulesFiles = require.context("./modules", false, /\.js$/);
let permission = getStorage("rolesId")?getStorage("rolesId"):[];
let modelRouter=modulesFiles.keys().filter((key) => {
  return permission.includes(modulesFiles(key).default.roleid)
}).map((modulePath) => modulesFiles(modulePath).default);


// let modelRouter = modulesFiles
//   .keys()
//   .map((modulePath) => modulesFiles(modulePath).default);
let authId = 0; // 权限id

// 根据菜单生成权限id
//（仅在叶子结点roles生成唯一id，父节点roles为子节点id集合）
modelRouter.forEach((first) => {
  first.children.forEach((two) => {
    if (two.children) {
      two.children.forEach((three) => {
        three.meta.roles = [++authId];
      });
      two.meta.roles = two.children.map((v) => v.meta.roles).flat();
    } else {
      two.meta.roles = [++authId];
    }
    first.meta.roles = first.children.map((v) => v.meta.roles).flat();
  });
});
export const auther = modelRouter;
//#endregion

// 静态路由
export const constantRoutes = [
  {
    path: "/login",
    component: () => import("@/views/login/index"),
    hidden: true,
  },

  {
    path: "/404",
    component: () => import("@/views/404"),
    hidden: true,
  },

  {
    path: "/",
    component: Layout,
    redirect: "/dashboard",
    children: [
      {
        path: "dashboard",
        name: "Dashboard",
        component: () => import("@/views/dashboard/index"),
        meta: { title: "概览", icon: "dashboard" },
      },
    ],
  },

  ...modelRouter,
];

// 异步路由
export const asyncRoutes = [
  // ...modelRouter,
  { path: "*", redirect: "/404", hidden: true },
];

const createRouter = () =>
  new Router({
    // mode: 'history', // require service support
    scrollBehavior: () => ({ y: 0 }),
    routes: constantRoutes,
  });

const router = createRouter();

// Detail see: https://github.com/vuejs/vue-router/issues/1234#issuecomment-357941465
export function resetRouter() {
  const newRouter = createRouter();
  router.matcher = newRouter.matcher; // reset router
}

export default router;
